import axios from "axios";
import {ElMessage} from "element-plus";
import {ServerInfo} from "@/config/ServerInfoConfig.js";
import {useUserStore} from "@/store/index.js";
import router from "@/router/index.js";

const waveRequest = axios.create({
    baseURL: ServerInfo.BASE_URL,
    timeout: 30000,
    withCredentials: true // 添加这行来携带cookie
});

// 添加请求拦截器
waveRequest.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
waveRequest.interceptors.response.use(function (response) {
    const userStore = useUserStore();
    if (response.data.success    === false && response.data.code === 700 && userStore.isLogin) {
        ElMessage.error('登录失效')
        router.replace('/login')
    }
    if (response.data.success === false && !String(response.code).charAt(0) === '3') {
        ElMessage.error(response.data.message)
        return response.data;
    }
    if (response.data.success === false) {
        ElMessage.error(response.data.message)
    }
    return response.data;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default waveRequest